﻿using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Moonwish.Core
{
    /// <summary>
    /// 缓存类，by zhlin 2011-08-06
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Cache<T> : Dictionary<string, ObservableCollection<T>>
    {
        public Cache()
        {
            Max = 10;
        }

        public string CurrentKey
        {
            get; set;
        }

        public int Max
        {
            get; set;
        }

        public new ObservableCollection<T> this[string key]
        {
            get
            {
                return base[key];
            }
            set
            {
                 if (!ContainsKey(key))
                {
                    RemoveFirst();
                }
                base[key] = value;
            }
        }

        public new void Add(string key, ObservableCollection<T> obj)
        {
            base.Add(key, obj);

            RemoveFirst();
        }

        void RemoveFirst()
        {
            if (Count > Max)
            {
                var keys = Keys.GetEnumerator();
                keys.MoveNext();
                Remove(keys.Current);
            }
        }

        public new void Remove(string key)
        {
            if (ContainsKey(key))
            {
                base.Remove(key);
            }
        }
    }
}
